package org.vsc.security;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import org.w3c.dom.Node;

public class KeyManager {
	private static String partnerId;
	private static String encryptAlgo;
	private static String privateKey;
	private static String publicKey;
	
	static {
		try {
			InputStream iss = KeyManager.class.getClassLoader().getResourceAsStream("org/vsc/security/config/config.xml");
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(iss);
			partnerId = doc.getElementsByTagName("partnerId").item(0).getFirstChild().getNodeValue();
			encryptAlgo = doc.getElementsByTagName("encryptAlgo").item(0).getFirstChild().getNodeValue();
			privateKey = doc.getElementsByTagName("privatekey").item(0).getFirstChild().getNodeValue();
			publicKey = doc.getElementsByTagName("publickey").item(0).getFirstChild().getNodeValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static PrivateKey getPrivateKeyFromPKCS8() throws NoSuchAlgorithmException, Exception {
		KeyFactory keyFactory = KeyFactory.getInstance(encryptAlgo);
		byte[] encodedKey = privateKey.getBytes();
		encodedKey = Base64.decodeBase64(encodedKey);
		return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
	}
	
	public static PublicKey getPublicKeyFromX509() throws NoSuchAlgorithmException, Exception{
		KeyFactory keyFactory = KeyFactory.getInstance(encryptAlgo);
		byte[] encodedKey = publicKey.getBytes();
		encodedKey = Base64.decodeBase64(encodedKey);
		return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
	}
}
